#include "../STL_MysqlConnPool.h"
#include <unistd.h>
#include <stdlib.h>
#include "STLOG.h"

using namespace STL;

void *handler(void *arg)
{
    long tid = (long)arg;

    std::cout << "tid =[" << tid << "]" << std::endl;
    STL_MysqlConnection *conn = STL_MysqlConnPool::getConnection();

    if (!conn)
    {
        std::cout << "getConnection NULL pointer" << std::endl;
        exit(-1);
    }

    //cout << "Connection.this:" << conn << endl;

    const char *query;
    query = "select * from channels;";

    try
    {
        STL_MysqlQueryResult queryResult = conn->executeQuery(query, tid);
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }
    try
    {
        STL_MysqlConnPool::releaseConnection(conn);
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }

    //for(int i=0;i<queryResult.getRowCount();i++){
    //	for(int j=0;j<queryResult.getColumnCount();j++){
    //		cout << queryResult.getElement(i,j) << " ";
    //	}
    //	cout << endl;
    //}
}

int main(int argc, char *argv[])
{
    std::string host = "localhost";
    uint16_t port = 3306;
    std::string user = "root";
    std::string pass = "123";
    std::string dbname = "videorelay";
    int poolSize = 1;

    STL_MysqlConnPool::initPool(host, port, user, pass, dbname, poolSize);

    for (size_t i = 0; i < 10000; i++)
    {
        STL_MysqlConnection *conn = STL_MysqlConnPool::getConnection();
        long tid = 0;
        STL_MysqlQueryResult result = conn->executeQuery("SELECT NOW() as 'date';", tid);
        std::string date = result.json_table[0]["date"].asString();
        stlog_info("%s", date.c_str());
        STL_MysqlConnPool::releaseConnection(conn);
        sleep(1);
    }

    stlog_error("over");

    // ///std::cin.get();

    // unsigned int count = -1;
    // if (argc > 1)
    // {
    //     count = atoi(argv[1]);
    // }

    // for (int i = 0; i < count; i++)
    // {

    //     const int THREAD_COUNT = 5;
    //     pthread_t threads[THREAD_COUNT];
    //     for (long i = 0; i < THREAD_COUNT; i++)
    //     {
    //         pthread_create(&threads[i], NULL, handler, (void *)i);
    //         //sleep(1);
    //     }

    //     for (int i = 0; i < THREAD_COUNT; i++)
    //     {
    //         pthread_join(threads[i], 0);
    //     }

    //     std::cout << "==============================LOOPBACK=================================" << std::endl;
    // }

    // STL_MysqlConnPool::destroyPool();

    return 0;
}